package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.constants.MQConstants;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.*;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Slf4j
@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SpuDetailMapper detailMapper;

    public PageResult<SpuDTO> querySpuByPage(String key, Integer page, Integer rows, Boolean saleable) {
        // 1.分页  limit 0, 10
        PageHelper.startPage(page, rows);
        // 2.创建条件
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        // 2.1.关键字过滤条件
        if (StringUtils.isNotBlank(key)) {
            // `name` LIKE '%X%'
            criteria.andLike("name", "%" + key + "%");
        }
        // 2.2.上下架过滤
        if (saleable != null) {
            // saleable = 1
            criteria.andEqualTo("saleable", saleable);
        }
        // 2.3.排序条件
        example.setOrderByClause("update_time DESC");

        // 3.查询数据
        List<Spu> list = spuMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }

        // 4.封装结果
        // 4.1.DTO的转换
        List<SpuDTO> items = BeanHelper.copyWithCollection(list, SpuDTO.class);
        // 4.2.分页结果
        PageInfo<Spu> info = new PageInfo<>(list);

        // 4.3.处理分类和品牌的名称
        handleCategoryAndBrandName(items);

        // 返回结果
        return new PageResult<>(info.getTotal(), info.getPages(), items);
    }

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    private void handleCategoryAndBrandName(List<SpuDTO> items) {
        for (SpuDTO spu : items) {

            /*List<CategoryDTO> list = categoryService.queryByIds(spu.getCategoryIds());
            StringBuilder sb = new StringBuilder();
            for (CategoryDTO categoryDTO : list) {
                sb.append(categoryDTO.getName()).append("/");
            }
            sb.deleteCharAt(sb.length() - 1);*/

            // 处理分类名称
            String categoryName = categoryService.queryByIds(spu.getCategoryIds())
                    .stream()
                    .map(CategoryDTO::getName)
                    .collect(Collectors.joining("/"));
            spu.setCategoryName(categoryName);

            // 处理品牌名称
            Long brandId = spu.getBrandId();
            BrandDTO brandDTO = brandService.queryById(brandId);
            spu.setBrandName(brandDTO.getName());
        }
    }

    @Autowired
    private SkuMapper skuMapper;

    @Transactional
    public void saveGoods(SpuDTO spuDTO) {
        try {
            // 1.新增spu
            Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
            // 默认商品是下架
            spu.setSaleable(false);
            int count = spuMapper.insertSelective(spu);
            if (count != 1) {
                throw new RuntimeException("新增spu失败！");
            }

            // 2.新增spuDetail
            SpuDetail spuDetail = BeanHelper.copyProperties(spuDTO.getSpuDetail(), SpuDetail.class);
            spuDetail.setSpuId(spu.getId());
            count = detailMapper.insertSelective(spuDetail);
            if (count != 1) {
                throw new RuntimeException("新增spuDetail失败！");
            }

            // 3.新增sku
            saveSku(spuDTO, spu);
        } catch (RuntimeException e) {
            log.error("新增商品失败，原因：{}", e.getMessage());
            throw new LyException(ExceptionEnum.INSERT_OPERATION_FAIL, e);
        }
    }

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Transactional
    public void updateSaleable(Long id, Boolean saleable) {
        try {
            // 1.更新spu
            Spu spu = new Spu();
            spu.setId(id);
            spu.setSaleable(saleable);
            int count = spuMapper.updateByPrimaryKeySelective(spu);
            if(count != 1) {
                throw new RuntimeException("更新spu的上下架失败。");
            }
            // 2.更新sku的enable
            // 2.1.更新的匹配条件
            Example example = new Example(Sku.class);
            example.createCriteria().andEqualTo("spuId", id);
            // 2.2.要更新的内容
            Sku sku = new Sku();
            sku.setEnable(saleable);
            skuMapper.updateByExampleSelective(sku, example);

            // 发送MQ消息
            String routingKey = saleable ? MQConstants.RoutingKey.ITEM_UP_KEY : MQConstants.RoutingKey.ITEM_DOWN_KEY;
            amqpTemplate.convertAndSend(
                    MQConstants.Exchange.ITEM_EXCHANGE_NAME, routingKey, id);

        } catch (RuntimeException e) {
            log.error("更新上下架状态失败，原因：{}", e.getMessage());
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }

    public SpuDetailDTO queryDetailBySpuId(Long id) {
        SpuDetail spuDetail = detailMapper.selectByPrimaryKey(id);
        if (spuDetail == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyProperties(spuDetail, SpuDetailDTO.class);
    }

    public List<SkuDTO> querySkuBySpuId(Long id) {
        Sku sku = new Sku();
        sku.setSpuId(id);
        List<Sku> list = skuMapper.select(sku);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SkuDTO.class);
    }

    @Transactional
    public void updateGoods(SpuDTO spuDTO) {
        // 1.删除sku
        Sku record = new Sku();
        record.setSpuId(spuDTO.getId());
        // 1.1.查询之前有几个sku
        int size = skuMapper.selectCount(record);
        if(size > 0) {
            int count = skuMapper.delete(record);
            if(count != size){
                throw new RuntimeException("删除sku失败！");
            }
        }
        // 2.修改spu
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);
        // 把不应该修改的字段，设置为null，避免一些错误的更新
        spu.setSaleable(null);
        spu.setCreateTime(null);
        int count = spuMapper.updateByPrimaryKeySelective(spu);
        if(count != 1){
            throw new RuntimeException("修改spu失败！");
        }
        // 3.修改spuDetail
        SpuDetail spuDetail = BeanHelper.copyProperties(spuDTO.getSpuDetail(), SpuDetail.class);
        count = detailMapper.updateByPrimaryKeySelective(spuDetail);
        if(count != 1){
            throw new RuntimeException("修改spuDetail失败！");
        }
        // 4.新增sku
        saveSku(spuDTO, spu);
    }

    private void saveSku(SpuDTO spuDTO, Spu spu) {
        int count;
        List<SkuDTO> skuDTOList = spuDTO.getSkus();

        List<Sku> skuList = new ArrayList<>();
        for (SkuDTO skuDTO : skuDTOList) {
            Sku sku = BeanHelper.copyProperties(skuDTO, Sku.class);
            sku.setSpuId(spu.getId());
            sku.setEnable(false);
            skuList.add(sku);
        }

        count = skuMapper.insertList(skuList);
        if (count != skuList.size()) {
            throw new RuntimeException("新增SKU失败！");
        }
    }

    public SpuDTO querySpuById(Long id) {
        // 根据主键查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        SpuDTO spuDTO = BeanHelper.copyProperties(spu, SpuDTO.class);
        // 查询sku
        spuDTO.setSkus(querySkuBySpuId(id));
        // 查询spuDetail
        spuDTO.setSpuDetail(queryDetailBySpuId(id));
        return spuDTO;
    }

    public List<SkuDTO> querySkuByIds(List<Long> ids) {
        List<Sku> list = skuMapper.selectByIdList(ids);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.GOODS_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SkuDTO.class);
    }

    @Transactional
    public void minusStock(Map<Long, Integer> skuMap) {
        // 遍历
        for (Map.Entry<Long, Integer> entry : skuMap.entrySet()) {
            Long skuId = entry.getKey();
            Integer num = entry.getValue();
            try {
                int count = skuMapper.minusStock(skuId, num);
                if(count != 1){
                    throw new RuntimeException("更新库存失败！");
                }
            } catch (Exception e) {
                throw new LyException(ExceptionEnum.STOCK_NOT_ENOUGH);
            }
        }
    }
}
